<?php
/*---------------------------------------------------------------------
 * 应用的公共的常用的全局函数
 * ---------------------------------------------------------------------
 * Copyright (c) 2013-now http://blog518.com All rights reserved.
 * ---------------------------------------------------------------------
 * Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
 * ---------------------------------------------------------------------
 * Author: <yangjian102621@gmail.com>
 *-----------------------------------------------------------------------*/

//获取appid

if (!function_exists('appId')) {
    function appId()
    {
	   if(defined('__APP_ID__')){
			return __APP_ID__;
	   }
	   return false;
       //return 'A7EBC-ACECD-HACBK-DYEEAC';
	   //return 'SNAKF-EEGBV-UYYZC-YYTREK';
    }
}
//获取当前管理员id

if (!function_exists('adminId')) {
    function adminId()
    {
		return \herosphp\bean\Beans::get('admin.adminManager.service')->getAdminId();
    }
}
if (!function_exists('adminName')) {
    function adminName()
    {
        return \herosphp\bean\Beans::get('admin.adminManager.service')->getAdminName();
    }
}
//获取全局语言配置

if (!function_exists('L')) {
    function L($key)
    {
        static $configs = NULL;
        if (!$configs) {
            $configs = include APP_PATH . '/configs/language.config.php';
        }
        return $configs[$key];
    }
}

//获取系统设置
if (!function_exists('C'))
{
	function C($item)
	{
		static $configService;
		if(!$configService)
		{
			$configService = \herosphp\bean\Beans::get('admin.adminSetting.service');
		}
		return $configService->getSetting($item);
	}
}

//加密方式
if (!function_exists('passwd')){
	function passwd($str){
		return md5(md5($str));
	}
}

/**
 * 拼接搜索字符串为sql
 * @param $data array('factory_name' => '三星塑料','product_name'='pvc')
 * @return array
 */
if (!function_exists('getStitchingSql')) {

    function getStitchingSql($data)
    {

        $conditions = array();

        foreach ($data as $k => $v) {

            if ($v !== '' && $v !== NULL) {

                $conditions[$k] = '%' . $v . '%';
            }
        }
        return $conditions;
    }
}

//select快捷设置

if (!function_exists('setSelectOptions')) {
    /**
     * @param $arr option项数组,例如：array('1'=>'卖家配送','2'=>'买家自提') --------- <option value="1">卖家配送</option>
     * @param $attributeName select的name值，例如：delivery_way --------- <select name="delivery_way">
     * @param string $defaultValue 默认值，例如：delivery_way --------- <option value="1" selected>卖家配送</option>
     * @param string $addAllOption 择增加一项开头option，例如：全部 --------- <option value="all" >全部</option>
     * @return string
     */
    function setSelectOptions($arr, $attributeName, $defaultValue = '', $addAllOption = '',$required='')
    {

        $options = '<select class="form-control input-sm" name="' . $attributeName . '" ' . $required . '>';

        if (strpos($addAllOption, '请选择') !== false) {

            $options .= '<option value="">' . $addAllOption . '</option>';

        } elseif ($addAllOption != '') {

            $options .= '<option value="all">' . $addAllOption . '</option>';

        }
        foreach ($arr as $k => $v) {

            if ($defaultValue == "$k") {

                $options .= '<option value="' . $k . '" selected>' . $v . '</option>';

            } else {

                $options .= '<option value="' . $k . '">' . $v . '</option>';
            }
        }

        return $options . '</select>';

    }
}
//checkbox快捷设置
if (!function_exists('setCheckboxOptions')) {
    /**
     * @param $arr option项数组,例如：array('1'=>'卖家配送','2'=>'买家自提') --------- <input type="checkbox" value="1">卖家配送
     * @param $attributeName input的name值，例如：delivery_way --------- <input type="checkbox" name="delivery_way">
     * @param string $defaultValue 默认值，例如：delivery_way --------- <input type="checkbox" value="1" selected>
     * @return string
     */
    function setCheckboxOptions($arr, $attributeName, $defaultValue = '')
    {

        $options = '';

        foreach ($arr as $k => $v) {

            $attributeId = 'checkbox_' .rand(1,1000).'_'. $k;

            $options .= '<div class="rdio rdio-primary" >';

            if (is_array($defaultValue)) {

                $bool = in_array($k, $defaultValue);
            } else {

                $bool = ($k == $defaultValue);
            }

            if ($bool) {

                $options .= '<input type="checkbox" name="' . $attributeName . '" value="' . $k . '" checked="checked" id = "' . $attributeId . '">';
                $options .= '<label for="' . $attributeId . '">' . $v . '</label>';

            } else {

                $options .= '<input type="checkbox" name="' . $attributeName . '" value="' . $k . '" id = "' . $attributeId . '">';
                $options .= '<label for="' . $attributeId . '">' . $v . '</label>';

            }
            $options .= '</div>';

        }

        return $options . '';

    }
}
//radio快捷设置

if (!function_exists('setRadioOptions')) {
    /**
     * @param $arr option项数组,例如：array('1'=>'卖家配送','2'=>'买家自提') --------- <input type="radio" value="1">卖家配送
     * @param $attributeName input的name值，例如：delivery_way --------- <input type="radio" name="delivery_way">
     * @param string $defaultValue 默认值，例如：delivery_way --------- <input type="radio" value="1" selected>
     * @return string
     */
    function setRadioOptions($arr, $attributeName, $defaultValue = '')
    {

        $options = '';

        foreach ($arr as $k => $v) {

            $attributeId = 'radio_' .rand(1,1000).'_'. $k;

            $options .= '<div class="rdio rdio-primary" >';

            if ($defaultValue == $k) {

                $options .= '<input type="radio" name="' . $attributeName . '" value="' . $k . '" checked="checked" id = "' . $attributeId . '">';
                $options .= '<label for="' . $attributeId . '">' . $v . '</label>';

            } else {

                $options .= '<input type="radio" name="' . $attributeName . '" value="' . $k . '" id = "' . $attributeId . '">';
                $options .= '<label for="' . $attributeId . '">' . $v . '</label>';

            }
            $options .= '</div>';

        }

        return $options . '';

    }
}

if (!function_exists('myNow')) {

    function myNow(){
        return date('Y-m-d H:i:s');
    }
}

/**
 * 删除文件操作
 * @param path 文件路径
 * @return int 返回值为0，表示删除成功，1表示删除失败，2表示文件不存在
 * coded by horse
 */
if(!function_exists("del_file"))
{
    function del_file($path)
    {
        if(file_exists($path))
        {
            if(unlink($path))
                return 0;
            else
                return 1;
        }
        else
            return 2;
    }
}
/*
 * 判断ip与ip段是否匹配
 * @param $ip : ip
 * @param $ipReg : ip 段 或 ip表达式
 * @return : boolean 
 */
 if(!function_exists('matchIp'))
 {
	function matchIp($ip,$ipReg){
	
		//127.0.0.1 match 127.0.0.1
		if($ip == $ipReg){
			return true;
		}
		$ipArr = explode('.',$ip);
		$ipRegArr = explode('.',$ipReg);
		//127.0.0.1 match 127.*
		if(count($ipRegArr) == 2 && $ipRegArr[1] == '*' && $ipArr[0] == $ipRegArr[0]){
			return true;
		}
		//127.0.0.1 match 127.0.*
		if(count($ipRegArr) == 3 && $ipRegArr[2] == '*' && $ipArr[0] == $ipRegArr[0] && $ipArr[1] == $ipRegArr[1]){
			return true;
		}
		//127.0.0.1 match 127.0.0.*
		if(count($ipRegArr) == 4 && $ipRegArr[3] == '*' && $ipArr[2] == $ipRegArr[2]
			&& $ipArr[1] == $ipRegArr[1] && $ipArr[0] == $ipRegArr[0])
		{
			return true;
		}

		if(count($ipRegArr) == 4){
			$unit = explode('/',$ipReg);
			//不是网段 127.0.0.1/xx
			if(count($unit) != 2){ return false;}
			$lip = ip2long($ip);
			$lipReg = ip2long($unit[0]);
			$mask = (1 << intval($unit[1])) - 1;
			//127.0.0.1 match 127.0.0.0/12
			if($lip & ~ $mask == $lipReg  & ~ $mask)
			{
				return true;
			}
		}
		return false;
	}

}
/**
 * 获取配置文档的值
 * @param $key
 * @return mixed
 */
/*
function getConfig($key) {

    if ( defined('RUN_CLI') ) {
        $appConfigs = Loader::config('app'); //加载当前应用的配置信息
        return $appConfigs[$key];
    } else {
        $webapp = \herosphp\core\WebApplication::getInstance();
        return $webapp->getConfig($key);
    }
}*/

function exportBtn(){
    echo '<button type="button" class="btn btn-sm btn-info pull-right" id="J_Export_btn"><i class="glyphicon glyphicon-save"></i> 导出Excel</button>';
}

/**
 * excel导出
 */
if (!function_exists('phpexcel')) {
    function phpexcel($name, $title, $data, $type = 1, $second_title = null, $second_data = null)
    {
        $objPHPExcel = new PHPExcel();
        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator('Fiidee.Monda.Cn')
            ->setLastModifiedBy("Fiidee.Monda.Cn")
            ->setTitle("Fiidee.Monda.Cn")
            ->setSubject("Fiidee.Monda.Cn")
            ->setDescription("Fiidee.Monda.Cn")
            ->setKeywords("Fiidee.Monda.Cn")
            ->setCategory("Fiidee.Monda.Cn");
        //以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle($name);
        $objPHPExcel->getActiveSheet()->getColumnDimension()->setAutoSize(true);
        //第一行默认为表头
        //在设置单元表格值的时候，前面加一个空格，可以强转为字符串，避免出现科学计数法
        $row = 1;
        if ($title && is_array($title)) {
            $col = 0;
            foreach ($title as $v) {
                $objPHPExcel->getActiveSheet()->
                setCellValueExplicit(chr($col+65).$row,$v,PHPExcel_Cell_DataType::TYPE_STRING);
                //setCellValueByColumnAndRow($col, $row, " ".$v);
                $col++;
            }
            $row++;
        }
        //表格内容
        foreach ($data as $k => $v) {
            $col = 0;
            foreach ($v as $val) {
                if ($col + 1 > count($title)) continue;
                $objPHPExcel->getActiveSheet()
                    ->setCellValueExplicit(chr($col+65).$row,$val,PHPExcel_Cell_DataType::TYPE_STRING);
                //->setCellValueByColumnAndRow($col, $row, " ".$val);
                $col++;
            }
            $row++;
        }
        if ($type == 2) {//多表 应用于财务账单列表
            $num = 1;
            foreach ($second_data as $k => $v) {
                if ($v)
                    $objPHPExcel->createSheet();
                $objPHPExcel->setActiveSheetIndex($num);
                $objPHPExcel->getActiveSheet()->setTitle($data[$k]['name'] . '清单');
                //第一行默认为表头
                $row = 1;
                $col = 0;
                if ($second_title && is_array($second_title)) {
                    foreach ($second_title as $val) {
                        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, " ".$val);
                        $col++;
                    }
                    $row++;
                }
                //表格内容
                foreach ($v as $val) {
                    $col = 0;
                    foreach ($val as $value) {
                        if ($col + 1 > count($second_title)) continue;
                        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, " ".$value);
                        $col++;
                    }
                    $row++;
                }
                $num++;
            }
        }

        $name = $name . date("YmdHis");
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

}
/**
 * 随机字符串
 * @param int $len
 * @return string
 */
if (!function_exists('getRandStr')) {
    function getRandStr($len=6){
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );
        $charsLen = count($chars) - 1;
        shuffle($chars);
        $output = "";
        for ($i=0; $i<$len; $i++)
        {
            $output .= $chars[mt_rand(0, $charsLen)];
        }
        return $output;
    }
}


/**
 * @param $num 需要转换的值
 * @param $length 小数点位数 默认2位
 * @return string
 */
if (!function_exists('setFloat')) {
    function setFloat($num, $length = 2)
    {
        return sprintf("%.{$length}f", $num);
    }
}
/**
 * 不区分大小写的in_array实现，一般用于权限开关
 * $value,
 * $array
 */
if (!function_exists('in_case_array')) {
    function in_case_array($value,$array)
    {
        return in_array(strtolower($value),array_map('strtolower',$array));
    }
}
if (!function_exists('isMobile')) {

    function isMobile($mobile)
    {
        if (!is_numeric($mobile)) {
            return false;
        }
        return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
    }
}